import React, { useState } from 'react';
import { Code, Save, Play, Eye, Undo, Redo, Grid, ZoomIn, ZoomOut, Download, Upload, Settings } from 'lucide-react';
import MenuToggle from '../components/MenuToggle';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';

const WorkflowDesign = ({ toggleSidebar }) => {
  const [workflowName, setWorkflowName] = useState('新建工作流');
  const [workflowDescription, setWorkflowDescription] = useState('');
  const [selectedNode, setSelectedNode] = useState(null);
  const [zoomLevel, setZoomLevel] = useState(100);

  // 节点类型
  const nodeTypes = [
    { id: 'start', name: '开始', icon: '🚀', color: 'bg-green-100 border-green-300' },
    { id: 'task', name: '任务', icon: '📋', color: 'bg-blue-100 border-blue-300' },
    { id: 'condition', name: '条件', icon: '❓', color: 'bg-yellow-100 border-yellow-300' },
    { id: 'approval', name: '审批', icon: '✅', color: 'bg-purple-100 border-purple-300' },
    { id: 'notification', name: '通知', icon: '📧', color: 'bg-orange-100 border-orange-300' },
    { id: 'end', name: '结束', icon: '🏁', color: 'bg-red-100 border-red-300' }
  ];

  // 模拟画布上的节点
  const [nodes, setNodes] = useState([
    {
      id: 'node-1',
      type: 'start',
      name: '流程开始',
      x: 100,
      y: 100,
      config: {}
    },
    {
      id: 'node-2',
      type: 'task',
      name: '数据处理',
      x: 300,
      y: 100,
      config: {
        script: 'console.log("处理数据");',
        timeout: 300
      }
    },
    {
      id: 'node-3',
      type: 'condition',
      name: '条件判断',
      x: 500,
      y: 100,
      config: {
        condition: 'data.status === "success"'
      }
    },
    {
      id: 'node-4',
      type: 'end',
      name: '流程结束',
      x: 700,
      y: 100,
      config: {}
    }
  ]);

  const handleNodeClick = (node) => {
    setSelectedNode(node);
  };

  const handleNodeUpdate = (nodeId, updates) => {
    setNodes(prev => prev.map(node => 
      node.id === nodeId ? { ...node, ...updates } : node
    ));
    if (selectedNode && selectedNode.id === nodeId) {
      setSelectedNode({ ...selectedNode, ...updates });
    }
  };

  const addNode = (type) => {
    const newNode = {
      id: `node-${Date.now()}`,
      type,
      name: nodeTypes.find(t => t.id === type)?.name || '新节点',
      x: 200 + Math.random() * 300,
      y: 200 + Math.random() * 200,
      config: {}
    };
    setNodes(prev => [...prev, newNode]);
  };

  const deleteNode = (nodeId) => {
    setNodes(prev => prev.filter(node => node.id !== nodeId));
    if (selectedNode && selectedNode.id === nodeId) {
      setSelectedNode(null);
    }
  };

  const handleSave = () => {
    console.log('保存工作流:', {
      name: workflowName,
      description: workflowDescription,
      nodes
    });
    alert('工作流已保存');
  };

  const handlePreview = () => {
    console.log('预览工作流');
    alert('预览功能开发中');
  };

  const handleExport = () => {
    const workflowData = {
      name: workflowName,
      description: workflowDescription,
      nodes,
      version: '1.0',
      exportTime: new Date().toISOString()
    };
    
    const blob = new Blob([JSON.stringify(workflowData, null, 2)], {
      type: 'application/json'
    });
    
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${workflowName}.json`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <>
      {/* 头部工具栏 */}
      <div className="mt-3">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl flex items-center justify-center">
                  <Code className="w-6 h-6 text-white" />
                </div>
                <div>
                  <Input
                    value={workflowName}
                    onChange={(e) => setWorkflowName(e.target.value)}
                    className="text-2xl font-bold border-none p-0 h-auto bg-transparent focus:ring-0"
                  />
                  <p className="text-sm text-material-grey-600">
                    可视化工作流设计器
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              <div className="flex items-center space-x-2 bg-material-grey-100 rounded-lg p-1">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setZoomLevel(prev => Math.max(50, prev - 10))}
                >
                  <ZoomOut className="w-4 h-4" />
                </Button>
                <span className="text-sm text-material-grey-600 px-2">{zoomLevel}%</span>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setZoomLevel(prev => Math.min(200, prev + 10))}
                >
                  <ZoomIn className="w-4 h-4" />
                </Button>
              </div>

              <Button variant="outline">
                <Undo className="w-4 h-4 mr-2" />
                撤销
              </Button>

              <Button variant="outline">
                <Redo className="w-4 h-4 mr-2" />
                重做
              </Button>

              <Button variant="outline" onClick={handleExport}>
                <Download className="w-4 h-4 mr-2" />
                导出
              </Button>

              <Button variant="outline" onClick={handlePreview}>
                <Eye className="w-4 h-4 mr-2" />
                预览
              </Button>

              <Button onClick={handleSave} className="bg-primary hover:bg-primary-600">
                <Save className="w-4 h-4 mr-2" />
                保存
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 flex">
        {/* 左侧：组件面板 */}
        <div className="w-80 bg-white border-r border-material-grey-200 flex flex-col">
          <div className="p-4 border-b border-material-grey-200">
            <h3 className="text-lg font-semibold text-material-grey-800">组件库</h3>
            <p className="text-sm text-material-grey-600">拖拽组件到画布</p>
          </div>
          
          <div className="flex-1 p-4 space-y-3">
            {nodeTypes.map((nodeType) => (
              <div
                key={nodeType.id}
                className={`p-3 rounded-lg border-2 border-dashed cursor-pointer hover:shadow-md transition-shadow ${nodeType.color}`}
                onClick={() => addNode(nodeType.id)}
              >
                <div className="flex items-center space-x-3">
                  <span className="text-2xl">{nodeType.icon}</span>
                  <div>
                    <p className="font-medium text-material-grey-800">{nodeType.name}</p>
                    <p className="text-xs text-material-grey-600">点击添加到画布</p>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* 中间：画布区域 */}
        <div className="flex-1 bg-material-grey-50 relative overflow-hidden">
          <div className="absolute inset-0 bg-grid-pattern opacity-10"></div>
          
          <div 
            className="relative w-full h-full"
            style={{ transform: `scale(${zoomLevel / 100})`, transformOrigin: 'top left' }}
          >
            {/* 网格背景 */}
            <div className="absolute inset-0">
              <svg className="w-full h-full">
                <defs>
                  <pattern id="grid" width="20" height="20" patternUnits="userSpaceOnUse">
                    <path d="M 20 0 L 0 0 0 20" fill="none" stroke="#e5e7eb" strokeWidth="1"/>
                  </pattern>
                </defs>
                <rect width="100%" height="100%" fill="url(#grid)" />
              </svg>
            </div>

            {/* 连接线 */}
            <svg className="absolute inset-0 w-full h-full pointer-events-none">
              {nodes.map((node, index) => {
                if (index < nodes.length - 1) {
                  const nextNode = nodes[index + 1];
                  return (
                    <line
                      key={`line-${node.id}-${nextNode.id}`}
                      x1={node.x + 60}
                      y1={node.y + 30}
                      x2={nextNode.x}
                      y2={nextNode.y + 30}
                      stroke="#6366f1"
                      strokeWidth="2"
                      markerEnd="url(#arrowhead)"
                    />
                  );
                }
                return null;
              })}
              <defs>
                <marker
                  id="arrowhead"
                  markerWidth="10"
                  markerHeight="7"
                  refX="9"
                  refY="3.5"
                  orient="auto"
                >
                  <polygon
                    points="0 0, 10 3.5, 0 7"
                    fill="#6366f1"
                  />
                </marker>
              </defs>
            </svg>

            {/* 节点 */}
            {nodes.map((node) => {
              const nodeType = nodeTypes.find(t => t.id === node.type);
              return (
                <div
                  key={node.id}
                  className={`absolute w-32 h-16 rounded-lg border-2 cursor-pointer transition-all hover:shadow-lg ${
                    nodeType?.color || 'bg-gray-100 border-gray-300'
                  } ${selectedNode?.id === node.id ? 'ring-2 ring-primary' : ''}`}
                  style={{ left: node.x, top: node.y }}
                  onClick={() => handleNodeClick(node)}
                >
                  <div className="flex items-center justify-center h-full p-2">
                    <div className="text-center">
                      <div className="text-lg mb-1">{nodeType?.icon}</div>
                      <div className="text-xs font-medium text-material-grey-800 truncate">
                        {node.name}
                      </div>
                    </div>
                  </div>
                  
                  {/* 删除按钮 */}
                  <button
                    className="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full text-xs hover:bg-red-600"
                    onClick={(e) => {
                      e.stopPropagation();
                      deleteNode(node.id);
                    }}
                  >
                    ×
                  </button>
                </div>
              );
            })}
          </div>
        </div>

        {/* 右侧：属性面板 */}
        <div className="w-80 bg-white border-l border-material-grey-200 flex flex-col">
          <div className="p-4 border-b border-material-grey-200">
            <h3 className="text-lg font-semibold text-material-grey-800">属性配置</h3>
            <p className="text-sm text-material-grey-600">
              {selectedNode ? `编辑 ${selectedNode.name}` : '选择节点进行配置'}
            </p>
          </div>
          
          <div className="flex-1 p-4">
            {selectedNode ? (
              <Tabs defaultValue="basic" className="w-full">
                <TabsList className="grid w-full grid-cols-2">
                  <TabsTrigger value="basic">基本</TabsTrigger>
                  <TabsTrigger value="advanced">高级</TabsTrigger>
                </TabsList>
                
                <TabsContent value="basic" className="space-y-4">
                  <div>
                    <Label htmlFor="node-name">节点名称</Label>
                    <Input
                      id="node-name"
                      value={selectedNode.name}
                      onChange={(e) => handleNodeUpdate(selectedNode.id, { name: e.target.value })}
                    />
                  </div>
                  
                  {selectedNode.type === 'task' && (
                    <div>
                      <Label htmlFor="node-script">执行脚本</Label>
                      <Textarea
                        id="node-script"
                        value={selectedNode.config.script || ''}
                        onChange={(e) => handleNodeUpdate(selectedNode.id, {
                          config: { ...selectedNode.config, script: e.target.value }
                        })}
                        rows={4}
                        placeholder="请输入执行脚本"
                      />
                    </div>
                  )}
                  
                  {selectedNode.type === 'condition' && (
                    <div>
                      <Label htmlFor="node-condition">条件表达式</Label>
                      <Input
                        id="node-condition"
                        value={selectedNode.config.condition || ''}
                        onChange={(e) => handleNodeUpdate(selectedNode.id, {
                          config: { ...selectedNode.config, condition: e.target.value }
                        })}
                        placeholder="例如: data.status === 'success'"
                      />
                    </div>
                  )}
                  
                  {selectedNode.type === 'approval' && (
                    <div>
                      <Label htmlFor="node-approver">审批人</Label>
                      <Select
                        value={selectedNode.config.approver || ''}
                        onValueChange={(value) => handleNodeUpdate(selectedNode.id, {
                          config: { ...selectedNode.config, approver: value }
                        })}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="选择审批人" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="admin">管理员</SelectItem>
                          <SelectItem value="manager">部门经理</SelectItem>
                          <SelectItem value="director">总监</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  )}
                </TabsContent>
                
                <TabsContent value="advanced" className="space-y-4">
                  <div>
                    <Label htmlFor="node-timeout">超时时间 (秒)</Label>
                    <Input
                      id="node-timeout"
                      type="number"
                      value={selectedNode.config.timeout || 300}
                      onChange={(e) => handleNodeUpdate(selectedNode.id, {
                        config: { ...selectedNode.config, timeout: parseInt(e.target.value) }
                      })}
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="node-retry">重试次数</Label>
                    <Input
                      id="node-retry"
                      type="number"
                      value={selectedNode.config.retryCount || 0}
                      onChange={(e) => handleNodeUpdate(selectedNode.id, {
                        config: { ...selectedNode.config, retryCount: parseInt(e.target.value) }
                      })}
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="node-description">节点描述</Label>
                    <Textarea
                      id="node-description"
                      value={selectedNode.config.description || ''}
                      onChange={(e) => handleNodeUpdate(selectedNode.id, {
                        config: { ...selectedNode.config, description: e.target.value }
                      })}
                      rows={3}
                      placeholder="请输入节点描述"
                    />
                  </div>
                </TabsContent>
              </Tabs>
            ) : (
              <div className="text-center py-12">
                <Settings className="w-12 h-12 mx-auto mb-4 text-material-grey-400" />
                <p className="text-material-grey-600">选择一个节点来配置其属性</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
};

export default WorkflowDesign;
